import {Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChange} from "@angular/core";
import {CommService} from "../comm-service";
import {MyhttpService} from "../myhttp.service";
import {SharedService} from "../shared-service";

declare var $: any;

@Component({
  selector: "video-tree2",
  template: `
    <div id="videotree2" class="videotree"></div>
  `,
  styles: [
    ".videotree{width: auto}",
  ]
})
export class VideoTree2Component implements OnInit, OnChanges {
  treetype: string;
  s_ksjhbh: string;
  s_ksccbh: string;
  frompage: string;


  /**
   *  场所业务树-----------------------------------
   * @param {string} flag
   * "" ----初始化构造
   * "refresh"---刷新场所树
   *
   * */
  initcsywtree(flag: string): void {
    this.frompage = this.o.frompage;
    if (flag == "refresh") {
      $("#videotree2").jstree("refresh");
      return;
    }
    const nodelx = this.o.nodelx;
    switch (nodelx) {
      case "mlsb":
        // 考点巡查， 和计划无关的视频查看
        this.createtree_mlsb();
        break;
    }
  }


  /**
   * 子节点是 sb
   */
  createtree_mlsb(): void {
    const that = this;
    $("#videotree2").jstree({
      "core": {
        "themes": {
          //如果使用 false默认主题则保留
          name: "default-dark",
          // 主题的CSS文件的URL，请保留该属性，就 false好像您已手动包含主题CSS（推荐）一样。您也可以将此设置为true 将尝试自动加载主题
          url: true,
          //所有jstree主题的位置-仅当 url 设置为时使用 true
          // 最终加载的css文件是  assets/jstreethemes/ 上面配置的name属性的值 /style.css【这里面的样式名要换成 上面配置的name属性的值】
          dir: "assets/jstreethemes",
          //指示是否显示连接点的布尔值
          dots: true,
          // 指示是否显示节点图标的布尔值
          icons: true,
          // 指示是否应显示节点省略号的布尔值-只能与容器上的固定with一起使用
          ellipsis: false,
          // 指示树背景是否为条纹的布尔值
          stripes: false,
          // 一个字符串（或boolean false），指定要使用的主题变体（如果主题支持变体）
          variant: false,
          //一个布尔值，指定主题的响应版本是否应在较小的屏幕上显示（如果主题支持）。默认为false.
          responsive: true,
        },
        data: function (node, cb) {
          if (node.id === "#") {
            that.getTree("-1", "-1", (data) => {
              const rootNode = {
                id: that.o.id,
                type: that.o.type,
                text: that.o.text,
                data: {},
                state: {
                  opened: true
                },
                children: data
              };
              cb(rootNode);
            });
          } else {
            const node_data = node.data;
            const nodetype = node.type;
            if (nodetype === "DG") {
              that.getTree(node_data.parentSipUri, node_data.uri, (data_data) => {
                cb(data_data);
              });
            } else if (nodetype === "DO") {
              that.getTree(node_data.uri, node_data.uri, (data_data) => {
                cb(data_data);
              });
            } else {
              const type_new = nodetype.split("|").includes("DO");
              if (type_new) {
                that.getTree(node_data.uri, node_data.uri, (data_data) => {
                  cb(data_data);
                });
              }
            }
          }
        }
      },
      "plugins": ["types"],
      "types": {
        "ksgljg": {
          "icon": "glyphicon glyphicon-home"
        },
        "DO": {
          "icon": "fa fa-university"
        },
        "DG": {
          "icon": "fa fa-university"
        },
        "DO|VU": {
          "icon": "fa fa-university"
        },
        "sb": {
          "icon": "fa fa-video-camera"
        }
      }
    }).on("select_node.jstree", function (e, selected) {
      const nodeobj = selected.node;
      const nodetype = nodeobj.type;
      if (nodetype == "sb") {
        const sipuri = nodeobj.data.uri;
        that.sharedService.emitChange({
          actiontype: "clicknode_sb",
          frompage: that.frompage,
          data: {
            nodeid: sipuri,
            nodetype: "sb"
          }
        });
      }
    })
  }

  getTree(sip: string, uri: string, callback: Function) {
    const url = "sbyw/sbtb/sipsbml";
    this.itservice.kwPtPost(url, {
      toSip: sip,
      requestUri: uri,
    }).subscribe(resp => {
      this.commservice.handResponse("get", url, resp, (flag, resp, flag2) => {
        if (flag) {
          if (flag2) {
            const treeList = resp.catalogs ? resp.catalogs : [];  // 目录
            const child_list = resp.deviceList == null ? [] : resp.deviceList;  // 设备
            const treelistFormater = treeList.map((item) => {
              const obj = {
                // id: item.uri,
                type: item.type,   // DO、 DG、DO｜VU
                text: item.name,
                data: item,
                children: true
              };
              return obj
            });
            const sbchildArr = child_list.map((item) => {
              return {
                // id: params.uri,
                type: "sb",
                text: item.name == null ? "123" : item.name,
                data: item,
                children: false,
                // a_attr: {
                //   style: item.staus == "ON" ? "color:green" : "color:yellow"
                // }
              }
            });
            callback(sbchildArr.length ? treelistFormater.concat(sbchildArr) : treelistFormater);
          } else {
            this.commservice.myswal("warning", resp, "", "ts", null);
            callback([]);
            return
          }
        } else {
          this.getTree(sip, uri, callback);
        }
      });
    });
  }


  /**
   * frompage
   * treetype  cstree---场所  ywtree---和考试计划考试场次有关系
   * nodelx  树上要挂的节点类型
   * id
   * type
   * text
   * ksjhbh---(ywtree)
   * ksccbh --(ywtree)
   * clickroot----(cstree)默认是true, false--不点击根节点
   */
  @Input() o: any;

  constructor(private  itservice: MyhttpService,
              private  commservice: CommService,
              private sharedService: SharedService) {

  }

  ngOnInit() {
    this.treetype = this.o.treetype;
    if (this.treetype == "csywtree") {
      this.initcsywtree("");
    }
  }

  ngOnChanges(changes: { [hs: string]: SimpleChange }) {
    const firstchange = changes.o.firstChange;
    if (!firstchange) {
      this.treetype = this.o.treetype;
      if (this.treetype == "csywtree") {
        this.initcsywtree("refresh")
      }
    }
  }
}
